/*
 * For com.royal.art
 * Copyright [2015/11/10] By FCHEN
 */
package com.commons.web;

import com.google.common.base.Joiner;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * RequestUtils
 * web请求工具类
 * @author FCHEN
 * @date 2015/11/10
 */
public final class RequestUtils {

    /**
     * 获取用户请求IP
     * @param request
     * @return
     */
    public final static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }

    /**
     * 获取非流的参数
     * @param request
     * @return
     */
    public final static String getRequestParams(HttpServletRequest request){
        @SuppressWarnings("unchecked")
        Map<String, String[]> params = request.getParameterMap();
        if(null == params || params.isEmpty())
            return "";
        StringBuilder queryString = new StringBuilder("");
        for (String key : params.keySet()) {
            String[] values = params.get(key);
            if(null == values){
                queryString.append(key).append("=").append("&");
            } else if(values.length == 1 ){
                queryString.append(key).append("=").append(values[0]).append("&");
            } else {
                queryString.append(key).append("=").append(Joiner.on(",").join(values)).append("&");
            }
        }
        return queryString.substring(0,queryString.length()-1);
    }


}
